package com.lcb.manager.web;

import com.alibaba.fastjson.JSON;
import com.lcb.manager.entity.Scientific;
import com.lcb.manager.util.MediaUploadUtil;
import com.lcb.manager.vo.Json;
import com.lcb.manager.repository.ScientificRepository;
import com.lcb.manager.vo.ScientificVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

@Controller
@RequestMapping("/scientific")
public class ScientificController {

    @Autowired
    private ScientificRepository scientificRepository;

    @RequestMapping(value = "/")
    public String index() {
        return "scientific";
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String getScientificInfo(@RequestParam int index) {
        Scientific scientific = null;
        String info;
        List<Scientific> scientificList = scientificRepository.findAll();
        if (index < 0) {
            index = 0;
            info = "已经是第一个了";
            scientific = scientificList.get(0);
        } else if (index > scientificList.size() - 1) {
            index = scientificList.size() - 1;
            info = "已经是最后一个了";
            scientific = scientificList.get(scientificList.size() - 1);
        } else {
            info = "null";
            scientific = scientificList.get(index);
        }
        ScientificVo scientificVo = ScientificVo.fromEntity(scientific);
        scientificVo.setIndex(index);
        scientificVo.setInfo(info);
        return JSON.toJSONString(scientificVo);
    }

    @ResponseBody
    @PostMapping("/add")
    public String add(@RequestParam("files") MultipartFile[] files,
                      @RequestParam("date") String date,
                      @RequestParam("title") String title,
                      @RequestParam("content") String content) {
        Json result = new Json();
        int fileLen = files.length;
        if (date.isEmpty() || title.isEmpty() || content.isEmpty()) {
            result.code = 1;
            result.msg = "请勿提交空数据！";
            return JSON.toJSONString(result);
        } else if (fileLen == 0) {
            result.code = 1;
            result.msg = "请选择图片！";
            return JSON.toJSONString(result);
        } else {
            Scientific scientific = new Scientific();
            List<String> imageNameList = MediaUploadUtil.uploadImages(files);
            scientific.setDate(Date.valueOf(date));
            scientific.setTitle(title);
            scientific.setContent(content);
            scientific.setPictures(JSON.toJSONString(imageNameList));
            scientificRepository.save(scientific);
            result.code = 0;
            result.msg = "提交成功！";
            return JSON.toJSONString(result);
        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public String edit(@RequestParam("files") MultipartFile[] files,
                       @RequestParam("id") int id,
                       @RequestParam("date") String date,
                       @RequestParam("title") String title,
                       @RequestParam("content") String content) throws IOException {
        Json result = new Json();

        int fileLen = files.length;
        if (date.isEmpty() || title.isEmpty() || content.isEmpty()) {
            result.code = 1;
            result.msg = "请勿提交空数据！";
            return JSON.toJSONString(result);
        } else if (fileLen == 0) {
            result.code = 1;
            result.msg = "请选择图片！";
            return JSON.toJSONString(result);
        } else {
            Scientific scientific = scientificRepository.findById(id).orElse(null);
            if (scientific != null) {
                List<String> imageNameList = MediaUploadUtil.uploadImages(files);
                scientific.setDate(Date.valueOf(date));
                scientific.setTitle(title);
                scientific.setContent(content);
                scientific.setPictures(JSON.toJSONString(imageNameList));
                scientificRepository.save(scientific);
            }
            result.code = 0;
            result.msg = "提交成功！";
            return JSON.toJSONString(result);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete")
    public String delete(@RequestParam int id) {
        Json result = new Json();
        scientificRepository.deleteById(id);
        result.code = 0;
        result.msg = "删除成功！";
        return JSON.toJSONString(result);
    }

    @ResponseBody
    @RequestMapping(value = "/list")
    public String getScientificList(@RequestParam(defaultValue = "") String date, @RequestParam int page, @RequestParam int limit) {
        Json result = new Json();
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<Scientific> pageResult;
        if (!date.isEmpty()) {
            String year = date.split("-")[0];
            String month = date.split("-")[1];
            pageResult = scientificRepository.findByDateOrderByDateAsc(year, month, pageable);
        } else {
            pageResult = scientificRepository.findByOrderByDateAsc(pageable);
        }
        result.code = 0;
        result.count = (int) pageResult.getTotalElements();
        result.data = pageResult.getContent();
        return JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd");
    }

    @RequestMapping(value = "/get_empty")
    public String getEmpty(ModelMap modelMap) {
        modelMap.put("title", "科研信息输入");
        modelMap.put("isEdit", false);
        return "_content";
    }

    @RequestMapping(value = "/get_one")
    public String getOne(ModelMap modelMap, @RequestParam int id) {
        Scientific scientific = scientificRepository.findById(id).orElse(null);
        ScientificVo vo = ScientificVo.fromEntity(scientific);
        modelMap.put("title", "科研信息输入");
        modelMap.put("isEdit", true);
        if (vo != null) {
            modelMap.put("vo", vo);
        }
        return "_content";
    }

}
